/**
 * @description 场外基金
 * @author wangjianjun
 */

import React, { PureComponent } from 'react';
import { NestedTableC, ExportC } from '../../../../comps';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Tooltip } from 'antd';
import { findTitleByValue, findValueByCode } from '../../../../utils/utils';
import { connect } from 'dva';
import TotalAccount from '../common/TotalAccount';
import SetColumns from '../common/SetColumns';
import MySwitch from '../common/mySwitch';
import _ from 'lodash';
import config from '../../../../comps/business/tradingMarket/config';
import configDirect from '../../../../comps/business/tradingDirect/config';
import myStyle from '../index.less';
import accounting from 'accounting';

@Form.create()
@connect(({ positionInquiryM, loading, globalM }) => ({
  positionInquiryM,
  loading: loading.effects['positionInquiryM/outsideFundsTable'],
  globalM,
}))
export default class OutsideFunds extends PureComponent {
  constructor(props) {
    super(props);
    this.scrollx = 0;
    this.newColumns = [];
    this.state = {
      search: {},
      columns: [],
      dataSource: [],
      page: 1,
      pageSize: 20,
      total: 0,
      account: {},
      treeData: [],
      checkedKeys: [],
      scrollx: 0,
      switchChecked: false, // 持仓穿透开关默认关闭
      columnsChild: [
        // 子表表头
        { title: '资产种类', key: 'assetClass' },
        { title: '资产代码', key: 'tradingCode' },
        { title: '证券名称', key: 'secuabbr' },
        { title: '交易市场', key: 'exchangeCode' },
        { title: '交易属性', key: 'attrCode' },
        { title: '持仓类型', key: 'holdType' },
        { title: '回购类型', key: 'buyBackType' },
        { title: '持仓数量', key: 'holdAmount', type: 'number', toFixed: 2 },
        { title: '市值', key: 'marketValue', type: 'money' },
        { title: '估值日期', key: 'valuationDate', type: 'date' },
      ],
      expandedRowKeys: [], // 展开的key
      filteredInfo: null, // 筛选value值集合
    };
  }

  componentDidMount() {
    const {
      dispatch,
      globalM: {
        dataDictionary: { LIMITATION_ASSET_TYPE = [], HOLD_TYPE = [], REPURCHASE_TYPE = [], ENTRUSTED_INVESTMENT_HOLD_ATTRCODE = [] },
      },
      outsideFundsArgs,
    } = this.props;
    // 债券默认查表头信息
    dispatch({
      type: 'positionInquiryM/queryShowCol',
      payload: {
        type: 'Trade_Ana_Fnd_Hold_Info',
      },
      callback: (data) => {},
    });
    // 子表格表头处理
    const childCols = this.state.columnsChild;
    childCols &&
      childCols.map((item) => {
        if (item.key == 'exchangeCode') {
          item.render = (text, record) => {
            if (text) {
              const findvalue = config.filter((item) => {
                return item.value == text;
              });
              if (findvalue && findvalue.length > 0) {
                return findvalue[0].title;
              } else {
                return '--';
              }
            } else {
              return '--';
            }
          };
        }
        if (item.key == 'holdType') {
          item.render = (text, record) => {
            if (text) {
              return findValueByCode(text, HOLD_TYPE);
            } else {
              return '--';
            }
          };
        }
        if (item.key == 'buyBackType') {
          item.render = (text, record) => {
            if (text) {
              return findValueByCode(text, REPURCHASE_TYPE);
            } else {
              return '--';
            }
          };
        }
        if (item.key == 'assetClass') {
          item.render = (text, record) => {
            if (text) {
              return findValueByCode(text, LIMITATION_ASSET_TYPE);
            } else {
              return '--';
            }
          };
        }
        if (item.key == 'attrCode') {
          item.render = (text, record) => {
            if (text) {
              return findValueByCode(text, ENTRUSTED_INVESTMENT_HOLD_ATTRCODE);
            } else {
              return '--';
            }
          };
        }
      });
    this.setState(
      {
        search: outsideFundsArgs,
        filteredInfo: null, // 重置筛选
        switchChecked: false, // 穿透开关关闭
        expandedRowKeys: [], // 展开的key
      },
      () => {
        this.getTableData();
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const init = !this.props.outsideFundsArgs ? '' : JSON.stringify(this.props.outsideFundsArgs);
    const initN = !nextProps.outsideFundsArgs ? '' : JSON.stringify(nextProps.outsideFundsArgs);

    if (init != initN) {
      this.setState(
        {
          search: nextProps.outsideFundsArgs,
          filteredInfo: null, // 重置筛选
          switchChecked: false, // 穿透开关关闭
          expandedRowKeys: [], // 展开的key
        },
        () => {
          this.getTableData();
        },
      );
    }
    if (this.props.resetTime != nextProps.resetTime) {
      this.setState({
        filteredInfo: null, // 重置筛选
        switchChecked: false, // 穿透开关关闭
        expandedRowKeys: [], // 展开的key
      });
    }
  }

  // 分页切换
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState({ filteredInfo: filter });
    if (current != this.state.page || pageSize != this.state.pageSize) {
      // 页码不同时候请求 避免筛选的时候发出清楚
      this.setState(
        {
          page: current,
          pageSize,
        },
        () => {
          this.getTableData('pageChange');
        },
      );
    }
  };

  // 查询表格数据

  getTableData = (type) => {
    const {
      dispatch,
      globalM: {
        dataDictionary: { fund_fundType = [] },
      },
    } = this.props;
    const { page, pageSize, search } = this.state;
    const params = {};
    params.pageSize = pageSize;
    if (type != 'pageChange') {
      // 点击查询按钮 重置页码
      this.setState({
        page: 1,
      });
      params.page = 1;
    } else {
      // 点击页码切换时候调用
      params.page = page;
    }
    this.setState({
      expandedRowKeys: [],
    });
    // 列表数据
    dispatch({
      type: 'positionInquiryM/outsideFundsTable',
      payload: {
        ...params,
        ...search,
        isETF: '1',
      },
      callback: (res) => {
        res.data &&
          res.data.map((item, key) => {
            item.key = key;
            item.fundType = findValueByCode(item.fundType, fund_fundType);
          });

        this.setState({
          dataSource: res.data,
          total: res.total,
        });
      },
    });
    if (type != 'pageChange') {
      // 获取统计信息
      dispatch({
        type: 'positionInquiryM/getSearchTotal',
        payload: {
          ...search,
          type: '2',
        },
        callback: (data) => {
          this.setState({
            account: data,
          });
        },
      });
    }
  };

  // 持仓穿透开关 开启或者关闭变化函数
  switchChange = (e) => {
    this.setState({
      switchChecked: e,
    });
    if (!e) {
      // 关闭则删除子项
      const dataSource = JSON.parse(JSON.stringify(this.state.dataSource));
      dataSource.map((item) => {
        if (item.nestedConfig) delete item.nestedConfig;
      });
      this.setState({ dataSource: [...dataSource], expandedRowKeys: [] });
    }
  };

  // 点击展开二级菜单
  onNestedExtend = (expanded, record) => {
    const { dispatch, outsideFundsArgs } = this.props;
    const dataSource = JSON.parse(JSON.stringify(this.state.dataSource));
    const index = dataSource.findIndex((item) => item.key === record.key);
    const data = this.state.expandedRowKeys || [];
    if (expanded) data.push(record.key);
    this.setState({
      expandedRowKeys: expanded ? data : data.filter((item) => item != record.key),
    });
    if (index > -1 && expanded) {
      // 这里写逻辑，处理数据
      dataSource[index].loading = true;
      this.setState(
        {
          dataSource: JSON.parse(JSON.stringify(dataSource)),
        },
        () => {
          // 获取穿透信息
          dispatch({
            type: 'positionInquiryM/getChildTableData',
            payload: {
              date: outsideFundsArgs.dataDt,
              exchangeCode: record?.id?.exchangecode, // 交易市场
              tradingCode: record.tradingcode,
              portfolioCode: record.portfolioInfoCode,
              securityType: '2', // 区分2-基金    理财资产管理计划-20   委外-21
            },
            callback: (datas) => {
              // 将获取到的子表格数据追加到数据中
              dataSource[index].loading = false;
              dataSource[index].nestedConfig = {
                rowKey: 'key',
                // columns: this.state.columnsChild,
                dataSource: datas,
                scroll: { x: 1200 },
                hidePage: true,
              };
              this.setState({
                dataSource: [...dataSource],
              });
            },
          });
        },
      );
    }
  };

  // 导出参数调整
  changeSearch() {
    const { search } = this.state;
    const newSearch = _.cloneDeep(search);
    if (newSearch && newSearch.fundId) {
      newSearch.fundId = newSearch.fundId.join(',');
    }
    newSearch.isETF = '1';
    return newSearch;
  }

  render() {
    const {
      positionInquiryM: { columnsInfo, checkedKeysInfo },
      loading,
    } = this.props;
    let { search, filteredInfo } = this.state;
    const columns = _.cloneDeep(columnsInfo[2].columns);
    this.newColumns = columns.filter((item) => item.display == true);
    filteredInfo = filteredInfo || {};
    if (this.newColumns && this.newColumns.length > 10) {
      const a = this.newColumns.length;
      this.scrollx = a * 150;
    } else {
      this.scrollx = 0;
    }

    this.newColumns.map((item) => {
      if (item.key == 'fundType') {
        item.filteredValue = filteredInfo.fundType || null;
        item.type = 'filterCol';
        item.width = '100px';
      }
      if (item.key == 'mvalue') {
        item.type = 'number';
      }
      if (item.key == 'enUnitCostPrice' || item.key == 'enUnitNav' || item.key == 'cost') {
        item.type = 'money';
        item.toFixed = 4;
      }

      if (item.key == 'marketValue' || item.key == 'enFloatProfit') {
        item.type = 'money';
      }
      if (item.key == 'investmentType') {
        item.title = (
          <span>
            投资类型
            <Tooltip title='展示的投资类型为同组合同标的的最近一次修改持仓操作'>
              <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
            </Tooltip>
          </span>
        );
      }

      if (item.key == 'id.dataDt') {
        item.render = (_, record) => {
          const text = record?.id?.dataDt;
          if (text != '--' && text) {
            return `${text.slice(0, 4)}-${text.slice(4, 6)}-${text.slice(6)}`;
          } else {
            return '--';
          }
        };
      }

      if (item.key == 'id.tradingcode') {
        item.render = (_, record) => {
          const text = record?.id?.tradingcode;
          if (text) {
            return text;
          } else {
            return '--';
          }
        };
      }
      if (item.key == 'jysc') {
        item.render = (text, record) => {
          if (record?.id?.exchangecode) {
            const findvalue = config.filter((item) => {
              return item.value == record.id.exchangecode;
            });
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            } else {
              return '--';
            }
          } else {
            return '--';
          }
        };
      }
    });

    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div style={{ flex: 1 }}>
            <TotalAccount account={this.state.account} type='0' />
          </div>
          <div>
            <MySwitch onChange={this.switchChange} checked={this.state.switchChecked} />
          </div>
          <div style={{ display: 'flex' }}>
            <div>
              <ExportC style={{ marginTop: '10px' }} url='api/v1/tradeAnaFndHoldInfo/exportFnd' search={this.changeSearch()} />
            </div>
            <div style={{ marginLeft: '5px', marginTop: '10px' }}>
              <SetColumns type='2' parameter='Trade_Ana_Fnd_Hold_Info' checkedKeysInfo={checkedKeysInfo} />
            </div>
          </div>
        </div>
        <NestedTableC
          columns={this.newColumns || []}
          dataSource={this.state.dataSource || []}
          onChange={this.handleTableChange}
          current={this.state.page}
          pageSize={this.state.pageSize}
          total={this.state.total}
          selfScrollY={true}
          scroll={{ x: this.scrollx }}
          loading={loading}
          rowKey={'key'}
          onExpand={this.onNestedExtend}
          expandedRowKeys={this.state.expandedRowKeys}
          fixedChild={true}
          childCols={this.state.columnsChild}
          rowClassName={(record) => (record.fundType === '私募' && this.state.switchChecked ? '' : myStyle.noExpend)} // 无子项 设置样式
          commonHeader={!this.state.switchChecked}
        />
      </div>
    );
  }
}
